<?php

/**
 * 验证服务
 * 登录、注册、修改密码、登出
 * 
 * /Apps/Common/Service/AuthService.class.php
 * 
 * Zix @ 2015-06-08
 */

namespace Common\Service;

use Common\Service\SysRoleService;
use Common\Service\MerchantService;

class AuthService {

  private static $instance;
  var $token_expried_time = 7200; //token  过期时间 2小时
  var $cookie_expried_time = 604800; //cookie 过期时间 7天

  public static function instance() {
    if (self::$instance == null) {
      $instance = new AuthService();
    }

    return $instance;
  }

  /**
   * 管理员登录
   * @param string $username
   * @param string $password
   * @param int    $remember
   * @param string $session_name
   * @return array ajax_arr
   */
  public function login_for_backend($username, $password, $remember, $session_name) {
    //检查用户名
    if (empty($username)) {
      return ajax_arr('用户名不能为空');
    }
    if (empty($password)) {
      return ajax_arr('密码不能为空');
    }

    $SysUser = M('SysUser');
    $data = $SysUser->where(' username = "%s"', $username)->find();

    if (empty($data)) {
      return ajax_arr('用户未找到');
    }
    if ($data['status'] == 5) {
      return ajax_arr('用户已禁用');
    }
    if ($data['status'] == 6) {
      return ajax_arr('用户待审核');
    }
    if ($data['password'] != md5($password)) {
      return ajax_arr('您输入的密码不正确');
    }

    //取用户角色信息
    $role_ret = $this->_get_role_data($data);
    if (!$role_ret['status']) {
      return $role_ret;
    }
    $data += $role_ret['data'];
    
    //取用户组信息
    $group_ret = $this->_get_group_data($data);
    if (!$group_ret['status']) {
      return $group_ret;
    }
    $data += $group_ret['data'];
    
    unset($data['password']);
    session($session_name, $data);
    $ret['token'] = $this->_after_login($data, $remember, $session_name);
    return ajax_arr('登录成功', TRUE, $ret);
  }

  /**
   * 取用户角色信息
   * @param type $data
   * @return type
   */
  function _get_role_data($data) {
    $SysRole = SysRoleService::instance();
    $role_data = $SysRole->get_by_user_id_for_auth($data['id']);
    if (empty($role_data)) {
      return ajax_arr('用户角色错误');
    }
    return ajax_arr('OK', TRUE, array(
      'data' => $role_data
    ));
  }
  
  /**
   * 取用户组信息
   * @param type $data
   * @return type
   */
  function _get_group_data($data) {
    $SysGroup = SysGroupService::instance();
    $group_data = $SysGroup->get_by_user_id_for_auth($data['id']);
    if (empty($group_data)) {
      return ajax_arr('用户组错误');
    }
    return ajax_arr('OK', TRUE, array(
      'data' => $group_data
    ));
  }

  /**
   * 管理员登录
   * @param string $username
   * @param string $password
   * @param int    $remember
   * @param string $session_name
   * @return array ajax_arr
   */
  public function login_for_mp($username, $password, $remember, $session_name) {
    //检查用户名
    if (empty($username)) {
      return ajax_arr('用户名不能为空');
    }
    if (empty($password)) {
      return ajax_arr('密码不能为空');
    }

    $SysUser = M('SysUser');
    $data = $SysUser->where(' username = "%s"', $username)->find();

    if (empty($data)) {
      return ajax_arr('用户未找到');
    }
    if ($data['status'] == 5) {
      return ajax_arr('用户已禁用');
    }
    if ($data['status'] == 6) {
      return ajax_arr('用户待审核');
    }
    if ($data['password'] != md5($password)) {
      return ajax_arr('您输入的密码不正确');
    }

    //取用户角色信息
    $role_ret = $this->_get_role_data($data);
    if (!$role_ret['status']) {
      return $role_ret;
    }
    $data += $role_ret['data'];
    
    //取用户组信息
    $group_ret = $this->_get_group_data($data);
    if (!$group_ret['status']) {
      return $group_ret;
    }
    $data += $group_ret['data'];
    
    unset($data['password']);
    
    //取商户信息
    $Merchant = MerchantService::instance();
    $data['mer_data'] = $Merchant->get_by_manager_user_id($data['id']);
    if ( empty( $data['mer_data'] ) ) {
      return ajax_arr('商户信息未找到');
    }
    
    session($session_name, $data);
    $ret['token'] = $this->_after_login($data, $remember, $session_name);
    return ajax_arr('登录成功', TRUE, $ret);
  }
  
  /**
   * 登录完成的处理
   * @param array $data
   * @param bool $remember
   * @param string $session_name
   * @return string
   */
  function _after_login($data, $remember, $session_name) {
    if (!empty($remember)) {
      cookie($session_name, $data['username'], $this->cookie_expried_time);
    }

    $login_data = array(
      'last_login' => date('Y-m-d H:i:s'),
    );

    //如果token过期 则更新
    if ($data['token_expired'] < time()) {
      $login_data['token'] = md5(rand_string(12));
      $login_data['token_expired'] = time() + $this->token_expried_time;
    }

    //生产token 写登录时间
    $SysUser = M('SysUser');
    $SysUser->where('id = %d', $data['id'])->save($login_data);

    //写统计
    return isset($login_data['token']) ? $login_data['token'] : $data['token'];
  }

  /**
   * 登出 删除session 和 cookie
   */
  public function logout($session_name, $session_menu_name) {
    session($session_name, null);
    session($session_menu_name, null);
    cookie($session_name, null);
  }

  /**
   * 判断是否登录
   * @param type $session_name
   * @return boolean
   */
  function is_login($session_name) {
    $auth = session($session_name);
    if ($auth && !empty($auth)) {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  /**
   * 修改密码
   * $config { '' }
   */
  public function chpass_backend($old_pwd, $pwd, $pwd_confirm, $session_name) {
    $auth = session($session_name);

    $uid = $auth['id'];

    if (empty($old_pwd)) {
      return ajax_arr('原密码不能为空');
    }

    $SysUser = M('SysUser');

    $userdata = $SysUser->where('id = %d', $uid)->find();

    if (empty($userdata)) {
      return ajax_arr('用户未找到');
    }

    if ($userdata['pwd'] != $old_pwd && $userdata['pwd'] != md5($old_pwd)) {
      return ajax_arr('原密码输入不正确');
    }
    if (empty($pwd)) {
      return ajax_arr('新密码不能为空');
    }
    if ($pwd != $pwd_confirm) {
      return ajax_arr('两次输入的密码不正确');
    }

    $ret = $SysUser->where('id = %d', $uid)->save(array(
      'pwd' => md5($pwd)
    ));

    if ($ret) {
      return ajax_arr('密码修改成功', TRUE);
    } else {
      return ajax_arr('密码修改失败，请稍后再试');
    }
  }
  
  function reset_pwd( $user_id ) {
    $SysUser = M('SysUser');
    
    $data = array(
      'password' => md5('123456'),
      'update_time' => date('Y-m-d H:i:s'),
    );
    
    $ret = $SysUser->where('id=%d' , $user_id)->save( $data );
    if ( $ret ) {
      return ajax_arr('用户密码已重置为：123456');
    } else {
      return ajax_arr('密码重置失败，请稍后再试');
    }
  }

}
